import os
import shutil
import time
from utils.log_util import get_logger

logger = get_logger()


def clean_directory(directory, retry=3, wait_time=1):
    """清空指定目录下的所有文件和子目录

    Args:
        directory: 目录路径
        retry: 删除失败时的重试次数
        wait_time: 重试前等待的秒数
    """
    if not os.path.exists(directory):
        logger.info(f"目录不存在: {directory}")
        return 0

    deleted_count = 0
    for item in os.listdir(directory):
        item_path = os.path.join(directory, item)
        deleted = False
        attempts = 0

        while not deleted and attempts < retry:
            try:
                if os.path.isfile(item_path):
                    os.remove(item_path)
                    deleted = True
                    deleted_count += 1
                    logger.info(f"已删除文件: {item}")
                elif os.path.isdir(item_path):
                    shutil.rmtree(item_path)
                    deleted = True
                    deleted_count += 1
                    logger.info(f"已删除目录: {item}")
            except Exception as e:
                attempts += 1
                if attempts < retry:
                    logger.warning(f"删除失败，尝试重试 ({attempts}/{retry}): {item_path}, 错误: {e}")
                    time.sleep(wait_time)  # 等待一段时间后重试
                else:
                    logger.error(f"删除失败，已达到最大重试次数: {item_path}, 错误: {e}")

    return deleted_count


def clean_reports():
    """清空测试报告目录"""
    reports_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "reports")
    count = clean_directory(reports_dir)
    logger.info(f"报告目录清理完成，共删除 {count} 个文件/目录")


def clean_logs():
    """清空日志目录"""
    logs_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logs")
    count = clean_directory(logs_dir)
    logger.info(f"日志目录清理完成，共删除 {count} 个文件/目录")


def clean_all():
    """清空所有指定目录"""
    logger.info("开始清理所有目录...")
    clean_reports()
    clean_logs()
    logger.info("清理操作全部完成")


if __name__ == "__main__":
    clean_all()